package com.algorithm.base.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 中序遍历
 * 左中右
 *
 * @author Amadeus
 * @date 2023/10/27
 */
public class InorderTraversal {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inOrder(root, list);
        return list;
    }

    public void inOrder(TreeNode node, List<Integer> list) {
        if (node == null) {
            return;
        }
        inOrder(node.left, list);
        list.add(node.val);
        inOrder(node.right, list);
    }

    public void inOrderIteration(TreeNode root, List<Integer> list) {
        Stack<TreeNode> stack = new Stack<>();
        //记录最左节点
        TreeNode node = root;

        while (node != null || !stack.isEmpty()) {
            while (node.left != null) {
                stack.push(node);
                node = node.left;
            }
            if (node.right == null) {
                list.add(stack.pop().val);
            } else {
                node = node.right;
            }
        }
    }
}
